-- ESTRUTURA DE LOG
DROP TABLE dbo.FR_LOG_TRIGGER
GO
CREATE TABLE dbo.FR_LOG_TRIGGER(
	LTR_COD	INT IDENTITY
	, LTR_TABELA SYSNAME
	, LTR_COLUNA SYSNAME 
	, LTR_OPERACAO CHAR(1)
	, LTR_CONTEUDO_ANTERIOR VARCHAR(8000)
	, LTR_CONTEUDO_ATUAL VARCHAR(8000)
	, LTR_DATA DATETIME
	, LTR_EQUIPAMENTO SYSNAME
	, LTR_USUARIO SYSNAME
	  CONSTRAINT PK_LOG_TRIGGER PRIMARY KEY (LTR_COD)
	)
GO
-- OBTEM TABELAS
DECLARE @LFCR CHAR(2), @SCRIPT1 SYSNAME, @SCRIPT2 SYSNAME, @TABLENAME SYSNAME, @TABLE_CR CURSOR, @COLUMN_CR CURSOR
SET @LFCR = CHAR(13) + CHAR(10)
SET @TABLE_CR  = CURSOR FOR 
	SELECT TOP 1 NAME FROM SYSOBJECTS 
		WHERE XTYPE = 'U' 
		AND XTYPE = 'U' 
		AND NAME NOT LIKE 'FR_%' 
		AND NAME NOT LIKE 'AA_%' 
		AND NAME NOT LIKE 'DTP%' 
		AND NAME NOT LIKE 'ELE%'
		ORDER BY NAME
OPEN @TABLE_CR
FETCH NEXT FROM @TABLE_CR INTO @TABLENAME
WHILE @@FETCH_STATUS = 0
BEGIN
	-- PRINT @NAME
	SET @SCRIPT1 = 'CREATE TRIGGER AD_LOG_#TABLE ON #TABLE FOR DELETE AS ' + @LFCR + ' BEGIN ' + @LFCR + '--#SRC ' + @LFCR + 'END'
	SET @SCRIPT1 = REPLACE(@SCRIPT1, '#TABLE', @TABLENAME)
	SET @SCRIPT2 = 'INSERT INTO FR_LOG_TRIGGER( LTR_TABELA, LTR_COLUNA, LTR_OPERACAO, LTR_CONTEUDO_ANTERIOR, LTR_CONTEUDO_ATUAL, LTR_DATA, LTR_EQUIPAMENTO, LTR_USUARIO) ' + @LFCR
				 + 'SELECT #TABLE,  '
	
	SET @COLUMN_CR = CURSOR FOR SELECT NAME FROM SYSCOLUMNS WHERE ID = OBJECT_ID( @TABLENAME )
	FETCH NEXT FROM @TABLE_CR INTO @TABLENAME
END
CLOSE @TABLE_CR
DEALLOCATE @TABLE_CR